<?php

class BaseController extends Yaf_Controller_Abstract
{
    public $request;
    public $response;
    public $session;
    public $config;
    protected $ispost;
    public $view;

    // 自动执行
    public function init()
    {
        //error_reporting(0);
        $this->view = $this->getView();
        // 设置Controller的模板位置为模块目录下的views文件夹
        $template_dir = APPLICATION_PATH . '/application/modules/' . $this->getModuleName() . '/views/';
        if ($this->getModuleName() == 'Index') $template_dir = APPLICATION_PATH . '/application/views';
        $this->setViewpath($template_dir);

        $this->request = $this->getRequest();
        $this->response = $this->getResponse();
        $this->session = Yaf_Session::getInstance();
        $this->config = Yaf_Registry::get('config');
        $this->ispost = $this->request->isPost();


        $this->view->assign('module', $this->request->getModuleName());
        $this->view->assign('controller', $this->request->getControllerName());
        $this->view->assign('action', $this->request->getActionName());

    }

    protected function post($var, $default = null)
    {
        $value = $this->request->getPost($var);
        if (is_array($value)) return $value;
        if (is_string($value)) return trim($value);
        if (!$value) return $default;
    }

    protected function get($var, $default = null)
    {
        $value = $this->request->getQuery($var);
        if (is_array($value)) return $value;
        if (is_string($value)) return trim($value);
        if (!$value) return $default;
    }

    // 返回
    protected function result($msg = '参数错误', $code = null, $data = [], $extdata = [])
    {
        header('content-type:application/json');
        if (is_null($code)) $code = 10001;
        $return = array(
            'code' => $code,
            'msg' => $msg
        );
        if ($data) $return['data'] = $data;
        $this->log('返回: ' . json_encode($return, JSON_UNESCAPED_UNICODE));
        die(json_encode(array_merge($return, $extdata), JSON_UNESCAPED_UNICODE));
    }


    // 显示错误界面
    protected function displayWarn($message, $template = 'error', $data = array())
    {
        if (isset($_REQUEST['isajax']) && $_REQUEST['isajax'] == 1) {
            $this->ajaxresult(1, $message, $data);
        }
        $this->view->assign('message', $message);
        $this->view->assign('warn_data', $data);
        $this->view->display(APPLICATION_PATH . "/application/views/error/{$template}.html");
        exit;
    }

    // 日志
    protected function log($data)
    {
        $path = $this->getModuleName() . '.' . $this->request->getControllerName() . '.' . $this->request->getActionName();
        Logger::getInterface($path)->error($data);
    }
}
